package cn.newgrand.netcall.muc;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.util.Collection;

import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;

import org.jivesoftware.resource.Res;
import org.jivesoftware.resource.SparkRes;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.Form;
import org.jivesoftware.smackx.FormField;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.spark.ChatManager;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.ui.ChatRoomNotFoundException;
import org.jivesoftware.spark.ui.ContactItem;
import org.jivesoftware.spark.ui.conferences.ConferenceUtils;
import org.jivesoftware.spark.ui.rooms.GroupChatRoom;
import org.jivesoftware.spark.util.ModelUtil;
import org.jivesoftware.spark.util.log.Log;

import cn.newgrand.netcall.component.BaseItem;
import cn.newgrand.netcall.component.ItemGroup;
/**
 * "我参加的群"面板组展示的实现，里面包含多个的chinagroup项 
 * 
 * @author sidneyren
 */
public class ChinaGroupItemGroup extends ItemGroup{
	private ChatManager chatManager;
	private ChinaGroupManager chinaGroupManager = ChinaGroupManager.getInstance();
	private String userJID = SparkManager.getSessionManager().getBareAddress();
	private ChinaGroupItem noItem = new ChinaGroupItem("nogroup","没有参与群聊",null);
	
	public ChinaGroupItemGroup(String groupName) {
		super(groupName);
		chatManager = SparkManager.getChatManager();
		addItem(noItem);
	}
	@Override
	public void doDoubleClick(BaseItem item) {
		enterRoom(item);
	}
	
	public void addItem(BaseItem item){
		super.addItem(item);
		//删除没有参与的群聊项
		if(getItems().size()>1){
			if(getItems().contains(noItem)){
				removeItem(noItem);
			}
		}
	}
	
	public void enterRoom(BaseItem item) {
//		try {
		GroupChatRoom gcr = chinaGroupManager.getCachedChinaGroups().get(item.getID());
		if(null==gcr) {
			return;
		}
		else{
			try{
			// Check if room already exists. If so, join room again.
	        try {
	            GroupChatRoom chatRoom = (GroupChatRoom)chatManager.getChatContainer().getChatRoom(item.getID());
	            MultiUserChat muc = chatRoom.getMultiUserChat();
	            //modified by sideny 
	            chatManager.getChatContainer().activateChatRoom(chatRoom);
	            return;
	        }
	        catch (ChatRoomNotFoundException e) {
	            // Nothing to do
	        }
//			try {
//				gcr.getMultiUserChat().getOwners();
//				gcr.getMultiUserChat().getAdmins();
//				gcr.getMultiUserChat().getMembers();
//				gcr.getMultiUserChat().getOccupants();
//			} catch (XMPPException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
	        ChatManager chatManager = SparkManager.getChatManager();
            chatManager.getChatContainer().addChatRoom(gcr);
            chatManager.getChatContainer().activateChatRoom(gcr);
			}catch (Exception e) {
				Log.error("打开的时候错误", e);
			}
		}
			
//			chatManager.getChatContainer().getChatRoom(item.getID());
//		} catch (ChatRoomNotFoundException e1) {
//			ConferenceUtils.joinConferenceOnSeperateThread(
//					item.getDisplayName(), item.getID(), null);
//		}
	}
	
	@Override
	public void firePopupEvent(MouseEvent e, final BaseItem item) {
		final JPopupMenu popup = new JPopupMenu();
		JMenuItem openGroup = new JMenuItem("打开");
		JMenuItem destoryGroupItem = new JMenuItem("销毁");
		JMenuItem exitGroupItem = new JMenuItem("退出");
		JMenuItem modGroupName = new JMenuItem("修改群名");
        GroupChatRoom gcr = chinaGroupManager.getCachedChinaGroup(item.getID());
        if(null != gcr){
        	popup.add(openGroup);
        	openGroup.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				enterRoom(item);
    			}
    		});
        	if(gcr.getConferenceRoomInfo().getOwners().contains(userJID)){
        		 popup.add(destoryGroupItem);
        		 popup.addSeparator();
        		 popup.add(modGroupName);
        		 destoryGroupItem.addActionListener(new DestoryAction(gcr));
        		 modGroupName.addActionListener(new ModGroupNameAction(item,gcr));
        	}else{
        		if(gcr.getConferenceRoomInfo().getMembers().contains(userJID))
        		popup.add(exitGroupItem);
        		popup.addSeparator();
        		exitGroupItem.addActionListener(new ExitAction(gcr));
        	}
        	 popup.show(this,e.getX(),e.getY()+22);
        }
//        popup.addSeparator();
	}
	
	class ModGroupNameAction implements ActionListener{
		final BaseItem item;
		private GroupChatRoom gcr ;
		public ModGroupNameAction(final BaseItem item,GroupChatRoom gcr){
			this.item = item;
			this.gcr = gcr;
		}
		
		@Override
		public void actionPerformed(ActionEvent e) {
			String oldName = item.getName();
			String newName = JOptionPane.showInputDialog(SparkManager.getMainWindow(), "新群名",oldName);
			if(ModelUtil.hasLength(newName) && !oldName.equals(newName)){
				try {
					//Form form = gcr.getMultiUserChat().getConfigurationForm().createAnswerForm();
					Form form = new Form(Form.TYPE_SUBMIT);
					FormField roomnameField = new FormField("muc#roomconfig_roomname");
					roomnameField.setType(FormField.TYPE_TEXT_SINGLE);
					roomnameField.addValue(newName);
					form.addField(roomnameField);
					//form.setAnswer("muc#roomconfig_roomname", newName);
					gcr.getMultiUserChat().sendConfigurationForm(form);
					item.setName(newName);
					gcr.setTabTitle(newName);
				} catch (XMPPException e1) {
					JOptionPane.showMessageDialog(SparkManager.getMainWindow(),"修改群名失败",Res.getString("title.error"), JOptionPane.ERROR_MESSAGE);
				}
			}
		}
		
	}
	
	class DestoryAction implements ActionListener{
		private GroupChatRoom gcr ;
		public DestoryAction(GroupChatRoom gcr) {
			this.gcr = gcr;
		}
		public void actionPerformed(ActionEvent e) {
			int i = JOptionPane.showConfirmDialog(SparkManager.getMainWindow(), "是否确定要删除？","销毁群", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
			if(i==JOptionPane.YES_OPTION){
				try {
					
					gcr.getMultiUserChat().destroy("管理员销毁","");
					//删除缓存map
					chinaGroupManager.removeCachedChinaGroup(gcr.getRoomname());
					//删除group面板中的item
					removeItem(getItemByID(gcr.getRoomname()));
				} catch (XMPPException e1) {
					JOptionPane.showMessageDialog(SparkManager.getMainWindow(),"群销毁失败",Res.getString("title.error"), JOptionPane.ERROR_MESSAGE);
				}
			}
		}
	}
	
	class ExitAction implements ActionListener{
		private GroupChatRoom gcr ;
		public ExitAction(GroupChatRoom gcr) {
			this.gcr = gcr;
		}
		public void actionPerformed(ActionEvent e) {
			int i = JOptionPane.showConfirmDialog(SparkManager.getMainWindow(), "是否确定要离开这个群？","离开群", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
			if(i==JOptionPane.YES_OPTION){
				gcr.getMultiUserChat().exit();
				chinaGroupManager.removeCachedChinaGroup(gcr.getName());
				chatManager.getChatContainer().removeChinaGroupRoom(gcr);
				removeItem(getItemByID(gcr.getRoomname()));
				
//				try {
//					gcr.getMultiUserChat().destroy("","");
//				} catch (XMPPException e1) {
//					JOptionPane.showMessageDialog(SparkManager.getMainWindow(),"离开群失败，请重试！",Res.getString("title.error"), JOptionPane.ERROR_MESSAGE);
//				}
			}
		}
	}
}
